{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>写游记 - 分享你的旅行故事</title>
    <!-- 引入 Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome -->
    <link rel="stylesheet" href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.css' %}">
    <!-- 引入简单的Markdown编辑器 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
    <style>
        :root {
            --primary-color: #ff6b6b;
            --secondary-color: #48dbfb;
            --accent-color: #1dd1a1;
            --dark-color: #2f3640;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f6fa;
            color: #333;
        }

        /* 导航条 - 保持与首页一致 */
        .navbar-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            padding: 0;
        }

        /* 页面标题区 */
        .page-header {
            background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url('{% static "img/write-bg.jpg" %}');
            background-size: cover;
            background-position: center;
            color: white;
            padding: 80px 0;
            text-align: center;
            margin-bottom: 30px;
        }

        .page-title {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 15px;
        }

        .page-subtitle {
            font-size: 1.1rem;
            max-width: 700px;
            margin: 0 auto;
        }

        /* 写游记表单 */
        .write-form {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 50px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: var(--dark-color);
            position: relative;
            padding-bottom: 10px;
        }

        .section-title:after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 40px;
            height: 3px;
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
        }

        /* 封面图片上传 */
        .cover-upload {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }

        .cover-upload:hover {
            border-color: var(--primary-color);
            background: rgba(255, 107, 107, 0.05);
        }

        .cover-upload i {
            font-size: 3rem;
            color: var(--primary-color);
            margin-bottom: 15px;
        }

        .cover-preview {
            max-width: 100%;
            max-height: 300px;
            display: none;
            margin: 0 auto 20px;
            border-radius: 5px;
        }

        /* 标签选择 */
        .tag-selector {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .tag-option {
            padding: 5px 15px;
            background: #f1f2f6;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            user-select: none;
        }

        .tag-option:hover {
            background: #dfe4ea;
        }

        .tag-option.selected {
            background: var(--primary-color);
            color: white;
        }

        /* 编辑器样式 */
        .editor-container {
            margin-bottom: 20px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .page-header {
                padding: 60px 0;
            }

            .page-title {
                font-size: 2rem;
            }
        }

    </style>
</head>
<body>
<!-- 导航条（与首页一致） -->
<nav class="navbar navbar-expand-lg navbar-dark navbar-custom sticky-top">
    <div class="container">
        <a class="navbar-brand" href="#">
            <i class="fa fa-map-marked-alt"></i> 旅游推荐系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link nav-link-custom" href="/homepage/"><i class="fa fa-home"></i> 首页</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link nav-link-custom" href="/travel/article/homepage/"><i class="fa fa-newspaper"></i>
                        旅游资讯</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link nav-link-custom active" href="#"><i class="fa fa-pen-fancy"></i> 写游记</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link nav-link-custom dropdown-toggle" href="#" id="navbarDropdown1" role="button"
                       data-bs-toggle="dropdown">
                        <i class="fa fa-compass"></i> 目的地推荐
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown1">
                        <li><a class="dropdown-item" href="#">国内热门</a></li>
                        <li><a class="dropdown-item" href="#">国外精选</a></li>
                    </ul>
                </li>
            </ul>
            <div class="d-flex align-items-center">
                <img src="{{ MEDIA_URL }}img/users/{{ user.id }}/avatar/avatar.jpg" class="rounded-circle me-2" width="40" height="40"
                     alt="用户头像">
                <span class="text-white me-3">欢迎，{{ user.nickname }}</span>
                <a href="/travel/article/homepage/" class="btn btn-sm btn-outline-light"><i class="fa fa-sign-out"></i> 退出</a>
            </div>
        </div>
    </div>
</nav>

<!-- 页面标题区 -->
<div class="page-header">
    <div class="container">
        <h1 class="page-title">分享你的旅行故事</h1>
        <p class="page-subtitle">记录旅途中的美好时刻，帮助更多旅行者发现世界的精彩</p>
    </div>
</div>

<div class="container">
    <!-- 写游记表单 -->
    <form class="write-form" id="travelArticleForm" enctype="multipart/form-data">
        {% csrf_token %}
        <!-- 基本信息区 -->
        <div class="form-section">

            <h3 class="section-title"><i class="fa fa-info-circle"></i> 基本信息</h3>
            <div class="mb-3">
                <label for="articleTitle" class="form-label" >游记标题</label>
                <input type="text" name="title" class="form-control" id="articleTitle" placeholder="例如：【云南之旅】10天9晚的浪漫邂逅"
                       required>
                <div class="form-text">一个好的标题能吸引更多读者</div>
            </div>

            <div class="mb-3">
                <label class="form-label">封面图片</label>
                <div class="cover-upload" id="coverUploadArea">
                    <i class="fa fa-camera"></i>
                    <p>点击上传游记封面图片</p>
                    <p class="text-muted">建议尺寸：1200×600像素，大小不超过5MB</p>
                    <input type="file" name="img" id="coverImage" accept="image/*" style="display: none;">
                </div>
                <img id="coverPreview" class="cover-preview" alt="封面预览">
            </div>
        </div>

        <!-- 旅行信息区 -->
<div class="form-section">

    <h3 class="section-title"><i class="fa fa-map-marked-alt"></i> 旅行信息</h3>
    <div class="row">
        <div class="col-md-4 mb-3">
            <label for="travelDays" class="form-label">旅行天数</label>
            <input type="number" name="days" class="form-control" id="travelDays" min="1" placeholder="例如：7" required>
        </div>
        <div class="col-md-4 mb-3">
            <label for="travelSeason" class="form-label">旅行季节</label>
            <select class="form-select" name="season"  id="travelSeason" required>
                <option value="" selected disabled>选择季节</option>
                <option value="spring">春季 (3-5月)</option>
                <option value="summer">夏季 (6-8月)</option>
                <option value="autumn">秋季 (9-11月)</option>
                <option value="winter">冬季 (12-2月)</option>
            </select>
        </div>
        <div class="col-md-4 mb-3">
            <label for="travelType" class="form-label">旅行类型</label>
            <select class="form-select" name="type" id="travelType" required>
                <option value="" selected disabled>选择旅行类型</option>
                <option value="free">自由行</option>
                <option value="group">跟团游</option>
                <option value="drive">自驾游</option>
                <option value="backpack">背包客</option>
                <option value="family">亲子游</option>
                <option value="honeymoon">蜜月旅行</option>
            </select>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 mb-3">
            <label for="travelContinent" class="form-label">所在大洲</label>
            <select class="form-select" name="state" id="travelContinent" required>
                <option value="" selected disabled>选择大洲</option>
                <option value="asia">亚洲</option>
                <option value="europe">欧洲</option>
                <option value="north_america">北美洲</option>
                <option value="south_america">南美洲</option>
                <option value="africa">非洲</option>
                <option value="oceania">大洋洲</option>
            </select>
        </div>
        <div class="col-md-4 mb-3">
            <label for="travelCountry" class="form-label">国家/地区</label>
            <select class="form-select" name="country" id="travelCountry" disabled required>
                <option value="" selected disabled>请先选择大洲</option>
            </select>
        </div>
        <div class="col-md-4 mb-3">
            <label for="travelCity" class="form-label">城市/省份</label>
            <select class="form-select" name="city" id="travelCity" disabled required>
                <option value="" selected disabled>请先选择国家</option>
            </select>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 mb-3">
            <label for="destination" class="form-label">具体目的地</label>
            <input type="text" name="destination" class="form-control" id="destination" placeholder="例如：大理古城、巴黎铁塔、西藏自驾等" required>
        </div>
        <div class="col-md-6 mb-3">
            <label for="travelDate" class="form-label">旅行时间</label>
            <input type="date" name="date" class="form-control" id="travelDate" required>
        </div>
    </div>
    <!-- 其他字段保持不变... -->
</div>

        <!-- 标签选择区 -->
        <div class="form-section">
            <h3 class="section-title"><i class="fa fa-tags"></i> 添加标签</h3>
            <p class="text-muted mb-3">选择合适的标签可以帮助更多人发现你的游记（最多选择5个）</p>

            <div class="tag-selector">
                <div class="tag-option" data-tag="自由行">自由行</div>
                <div class="tag-option" data-tag="自驾游">自驾游</div>
                <div class="tag-option" data-tag="跟团游">跟团游</div>
                <div class="tag-option" data-tag="背包客">背包客</div>
                <div class="tag-option" data-tag="亲子游">亲子游</div>
                <div class="tag-option" data-tag="蜜月旅行">蜜月旅行</div>
                <div class="tag-option" data-tag="美食之旅">美食之旅</div>
                <div class="tag-option" data-tag="摄影之旅">摄影之旅</div>
                <div class="tag-option" data-tag="徒步">徒步</div>
                <div class="tag-option" data-tag="登山">登山</div>
                <div class="tag-option" data-tag="海岛度假">海岛度假</div>
                <div class="tag-option" data-tag="城市探索">城市探索</div>
            </div>
            <input type="hidden" id="selectedTags" name="tags">
        </div>

        <!-- 游记内容区 -->
        <div class="form-section">
            <h3 class="section-title"><i class="fa fa-edit"></i> 游记内容</h3>
            <div class="mb-3">
                <label for="articleSummary" class="form-label">游记简介</label>
                <textarea class="form-control" name="introduction" id="articleSummary" rows="3" placeholder="用一段简短的话概括你的旅行体验"
                          required></textarea>
                <div class="form-text">这将是读者看到的第一段内容，尽量简洁有趣</div>
            </div>

            <div class="mb-3">
                <label class="form-label">详细内容</label>
                <div class="editor-container">
                    <textarea id="articleContent" name="content" placeholder="在这里写下你的旅行故事..."></textarea>
                </div>
                <div class="form-text">支持Markdown语法，可以插入图片、链接等</div>
            </div>
        </div>

        <!-- 图片上传区 -->
        <div class="form-section">
            <h3 class="section-title"><i class="fa fa-images"></i> 上传图片</h3>
            <div class="mb-3">
                <label for="travelImages" class="form-label">添加旅行照片</label>
                <input type="file" class="form-control" name="travelImages" id="travelImages" multiple accept="image/*">
                <div class="form-text">可以一次选择多张图片（最多20张）</div>
            </div>
            <div class="row" id="imagePreviewContainer">
                <!-- 图片预览将在这里动态生成 -->
            </div>
        </div>

        <!-- 提交按钮 -->
        <div class="d-flex justify-content-between mt-5">
            <button type="button" class="btn btn-outline-secondary" id="saveDraft">
                <i class="fa fa-save"></i> 保存草稿
            </button>
            <div>
                <button type="button" class="btn btn-outline-primary me-2" id="previewArticle">
                    <i class="fa fa-eye"></i> 预览
                </button>
                <button type="submit" class="btn btn-primary" id="submitArticle">
                    <i class="fa fa-paper-plane"></i> 发布游记
                </button>
            </div>
        </div>
    </form>
</div>

<!-- 引入 Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- 引入 Markdown 编辑器 -->
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
<script>
    // 初始化Markdown编辑器
    const simplemde = new SimpleMDE({
        element: document.getElementById("articleContent"),
        placeholder: "在这里写下你的旅行故事...",
        spellChecker: false,
        autoDownloadFontAwesome: false,
        toolbar: ["bold", "italic", "heading", "|", "quote", "unordered-list", "ordered-list", "|", "link", "image", "|", "preview", "guide"]
    });

    // 封面图片上传预览
    const coverUploadArea = document.getElementById('coverUploadArea');
    const coverImageInput = document.getElementById('coverImage');
    const coverPreview = document.getElementById('coverPreview');

    coverUploadArea.addEventListener('click', () => coverImageInput.click());

    coverImageInput.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (event) {
                coverPreview.src = event.target.result;
                coverPreview.style.display = 'block';
                coverUploadArea.style.display = 'none';
            };
            reader.readAsDataURL(file);
        }
    });

    // 标签选择逻辑
    const tagOptions = document.querySelectorAll('.tag-option');
    const selectedTagsInput = document.getElementById('selectedTags');
    let selectedTags = [];

    tagOptions.forEach(tag => {
        tag.addEventListener('click', function () {
            const tagValue = this.getAttribute('data-tag');

            if (this.classList.contains('selected')) {
                // 取消选择
                this.classList.remove('selected');
                selectedTags = selectedTags.filter(t => t !== tagValue);
            } else {
                // 检查是否已达到最大选择数量
                if (selectedTags.length >= 5) {
                    alert('最多只能选择5个标签');
                    return;
                }
                // 选择标签
                this.classList.add('selected');
                selectedTags.push(tagValue);
            }

            // 更新隐藏输入框的值
            selectedTagsInput.value = selectedTags.join(',');
        });
    });

    // 多图片上传预览
    const travelImagesInput = document.getElementById('travelImages');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');

    travelImagesInput.addEventListener('change', function (e) {
        imagePreviewContainer.innerHTML = ''; // 清空预览容器

        const files = e.target.files;
        if (files.length > 20) {
            alert('最多只能上传20张图片');
            this.value = ''; // 清空文件选择
            return;
        }

        for (let i = 0; i < Math.min(files.length, 20); i++) {
            const file = files[i];
            const reader = new FileReader();

            reader.onload = function (event) {
                const col = document.createElement('div');
                col.className = 'col-6 col-md-4 col-lg-3 mb-3';

                const imgContainer = document.createElement('div');
                imgContainer.className = 'position-relative';

                const img = document.createElement('img');
                img.src = event.target.result;
                img.className = 'img-fluid rounded';
                img.style.height = '100px';
                img.style.width = '100%';
                img.style.objectFit = 'cover';

                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'btn btn-sm btn-danger position-absolute top-0 end-0';
                deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
                deleteBtn.style.transform = 'translate(50%, -50%)';
                deleteBtn.onclick = function () {
                    col.remove();
                    // 这里还需要从FileList中移除对应的文件
                };

                imgContainer.appendChild(img);
                imgContainer.appendChild(deleteBtn);
                col.appendChild(imgContainer);
                imagePreviewContainer.appendChild(col);
            };

            reader.readAsDataURL(file);
        }
    });

    // 表单提交
    // 表单提交
document.getElementById('travelArticleForm').addEventListener('submit', function (e) {
    e.preventDefault();

    // 收集表单数据
    const formData = new FormData(this);

    // 添加Markdown编辑器内容
    formData.append('content', simplemde.value());

    // 显示加载状态
    const submitBtn = document.getElementById('submitArticle');
    submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 发布中...';
    submitBtn.disabled = true;

    // 发送AJAX请求
    fetch(`/add/${ {{ user.id }} }/travel/article/`, {
    method: 'POST',
    body: formData,
    headers: {
        'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
    }
})
    .then(response => response.json())
    .then(data => {
    if (data.status === 'success') {  // 改为检查status字段
        alert('游记发布成功！');
        window.location.href = '/travel/article/homepage/';
    } else {
        alert('发布失败: ' + (data.message || '未知错误'));
    }
})
    .catch(error => {
        console.error('Error:', error);
        alert('发布过程中出现错误');
        submitBtn.innerHTML = '<i class="fa fa-paper-plane"></i> 发布游记';
        submitBtn.disabled = false;
    });
});

    // 保存草稿
    document.getElementById('saveDraft').addEventListener('click', function () {
        // 这里可以添加保存草稿的逻辑
        alert('草稿已保存');
    });

    // 预览功能
    document.getElementById('previewArticle').addEventListener('click', function () {
        // 这里可以添加预览逻辑
        alert('预览功能将在新窗口打开');
    });

    // 国家数据 - 按大洲分类的热门国家
const countryData = {
    asia: [
        {name: "中国", cities: ["北京", "上海", "广州", "深圳", "成都", "重庆", "杭州", "武汉", "西安", "南京", "其他城市"]},
        {name: "日本", cities: ["东京", "大阪", "京都", "札幌", "福冈", "名古屋", "冲绳", "其他城市"]},
        {name: "韩国", cities: ["首尔", "釜山", "济州岛", "仁川", "其他城市"]},
        {name: "泰国", cities: ["曼谷", "清迈", "普吉岛", "芭堤雅", "其他城市"]},
        {name: "其他亚洲国家", cities: ["其他城市"]}
    ],
    europe: [
        {name: "法国", cities: ["巴黎", "里昂", "马赛", "尼斯", "其他城市"]},
        {name: "意大利", cities: ["罗马", "米兰", "威尼斯", "佛罗伦萨", "其他城市"]},
        {name: "德国", cities: ["柏林", "慕尼黑", "法兰克福", "汉堡", "其他城市"]},
        {name: "英国", cities: ["伦敦", "爱丁堡", "曼彻斯特", "利物浦", "其他城市"]},
        {name: "其他欧洲国家", cities: ["其他城市"]}
    ],
    north_america: [
        {name: "美国", cities: ["纽约", "洛杉矶", "旧金山", "芝加哥", "其他城市"]},
        {name: "加拿大", cities: ["多伦多", "温哥华", "蒙特利尔", "其他城市"]},
        {name: "其他北美洲国家", cities: ["其他城市"]}
    ],
    south_america: [
        {name: "巴西", cities: ["里约热内卢", "圣保罗", "其他城市"]},
        {name: "阿根廷", cities: ["布宜诺斯艾利斯", "其他城市"]},
        {name: "其他南美洲国家", cities: ["其他城市"]}
    ],
    africa: [
        {name: "埃及", cities: ["开罗", "亚历山大", "其他城市"]},
        {name: "南非", cities: ["开普敦", "约翰内斯堡", "其他城市"]},
        {name: "其他非洲国家", cities: ["其他城市"]}
    ],
    oceania: [
        {name: "澳大利亚", cities: ["悉尼", "墨尔本", "布里斯班", "其他城市"]},
        {name: "新西兰", cities: ["奥克兰", "惠灵顿", "其他城市"]},
        {name: "其他大洋洲国家", cities: ["其他城市"]}
    ]
};

// 中国省份数据
const chinaProvinces = [
    "北京", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江",
    "上海", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南",
    "湖北", "湖南", "广东", "广西", "海南", "重庆", "四川", "贵州",
    "云南", "西藏", "陕西", "甘肃", "青海", "宁夏", "新疆", "台湾",
    "香港", "澳门"
];

// 获取DOM元素
const travelContinent = document.getElementById('travelContinent');
const travelCountry = document.getElementById('travelCountry');
const travelCity = document.getElementById('travelCity');

// 初始化国家下拉框
function initCountrySelect(continent) {
    travelCountry.innerHTML = '<option value="" selected disabled>选择国家</option>';
    travelCountry.disabled = false;

    countryData[continent].forEach(country => {
        const option = document.createElement('option');
        option.value = country.name;
        option.textContent = country.name;
        travelCountry.appendChild(option);
    });

    // 重置城市选择
    travelCity.innerHTML = '<option value="" selected disabled>请先选择国家</option>';
    travelCity.disabled = true;
}

// 初始化城市下拉框
function initCitySelect(countryName, continent) {
    travelCity.innerHTML = '<option value="" selected disabled>选择城市/省份</option>';
    travelCity.disabled = false;

    if (countryName === "中国") {
        // 中国特殊处理 - 显示所有省份
        chinaProvinces.forEach(province => {
            const option = document.createElement('option');
            option.value = province;
            option.textContent = province;
            travelCity.appendChild(option);
        });
    } else {
        // 其他国家 - 显示预定义的热门城市
        const country = countryData[continent].find(c => c.name === countryName);
        if (country) {
            country.cities.forEach(city => {
                const option = document.createElement('option');
                option.value = city;
                option.textContent = city;
                travelCity.appendChild(option);
            });
        }
    }
}

// 大洲选择变化事件
travelContinent.addEventListener('change', function() {
    const continent = this.value;
    initCountrySelect(continent);
});

// 国家选择变化事件
travelCountry.addEventListener('change', function() {
    const countryName = this.value;
    const continent = travelContinent.value;
    initCitySelect(countryName, continent);
});

// 表单提交验证
document.getElementById('travelArticleForm').addEventListener('submit', function(e) {
    if (!travelContinent.value || !travelCountry.value || !travelCity.value) {
        alert('请完整选择旅行地区信息');
        e.preventDefault();
        return;
    }
    // 其他验证逻辑...
});
</script>
</body>
</html>